#ifndef __DATA_BASE_H__
#define __DATA_BASE_H__

#include "Mutex.h"
#include <string>
#include <list>

typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;

class IError;
class Query;
class Mutex;

struct sDBHandler
{
	sDBHandler():busy(false){}
	MYSQL mysql;
	bool busy;
};
typedef std::list<sDBHandler*> ListHandler;

class DataBase
{
public:
	DataBase(const std::string &host, const std::string &user, const std::string &password = "", const std::string &database = "", IError *e = NULL, DWORD dwClientFlag = 0);
	DataBase(Mutex &mutex, const std::string &host, const std::string &user, const std::string &password = "", const std::string &database = "", IError *e = NULL, DWORD dwClientFlag = 0);

	virtual ~DataBase();

	enum eTimeOutOption
	{
		eConnect,
		eRead,
		eWrite,
	};

	bool SetTimeOut(sDBHandler *hDb, eTimeOutOption opt, int sec = 1);
	bool IsConnected();
	void RegisterErrorHandler(IError *e);
	void Error(Query &, const char *fmt, ...);

	sDBHandler *GetValidHandler(int nSecond = 1);
	void FreeHandler(sDBHandler *hDb);

private:
	DataBase(const DataBase&):m_Mutex(m_Mutex){}
	DataBase &operator=(const DataBase &){return *this;}

	void Error(const char *fmt, ...);

private:
	std::string m_strHost;
	std::string m_strUser;
	std::string m_strPass;
	std::string m_strDB;
	ListHandler m_lDBHandlers;
	IError *m_errHandler;
	Mutex &m_Mutex;
	bool m_bUseMutex;
	DWORD m_dwClientFlag;
};
#endif